package com.tina.listener;

import java.util.concurrent.atomic.AtomicInteger;

import com.tina.entity.TiOnline;
import com.tina.handle.BeanHeader;
import com.tina.service.TiOnlineService;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

/**
 * Shiro会话监听器
 *
 * @author Tina
 */
public class ShiroSessionListener implements SessionListener{

    private final AtomicInteger sessionCount = new AtomicInteger(0);

    private Logger logger = LoggerFactory.getLogger(ShiroSessionListener.class);


    public  boolean forceUserLogout(String sessionId) {
        if (sessionId != null) {
            TiOnline online = new TiOnline();
            online.setOnlineSessionId(sessionId);
            online.setOnlineState(1);
            TiOnlineService beanTiOnlineService = BeanHeader.getBean(TiOnlineService.class);
            boolean editOnlineStateById = beanTiOnlineService.updateById(online);
            return editOnlineStateById;
        }
        return false;
    }

    @Override
    public void onStart(Session session) {
        System.out.println("会话创建：" + session.getId());
        sessionCount.incrementAndGet();
    }

    @Override
    public void onStop(Session session) {
        System.out.println("停止会话：" + session.getId());
        boolean forceLogoutOnStop = forceUserLogout((String) session.getId());
        logger.info("forceLogoutOnStop={}", forceLogoutOnStop);
        sessionCount.decrementAndGet();
    }

    @Override
    public void onExpiration(Session session) {
        System.out.println("超时会话：" + session.getId());
        boolean forceLogoutOnExpiration =forceUserLogout((String) session.getId());
        logger.info("forceLogoutOnExpiration={}", forceLogoutOnExpiration);
        sessionCount.decrementAndGet();
    }


}
